package session;

import core.Config;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

public class ClientSession extends Session {
    private static SocketChannel socketChannel;
    private static Selector selector;

    public ClientSession(Config config) throws IOException {
        super(config);
        selector = Selector.open();

        socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(config.getHost(), config.getPort()));
        socketChannel.configureBlocking(false);

        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    @Override
    public void close() throws Exception {
        socketChannel.close();
    }

    @Override
    public void run() {
        new Thread(this::in_read).start();
        new Thread(() -> {
            while (true) {
                try {
                    selector.select(); // blocking

                    Iterator<SelectionKey> keysIterator = selector.selectedKeys().iterator();
                    while (keysIterator.hasNext()) {
                        SelectionKey key = keysIterator.next();

                        if (key.isReadable()) {
                            keysIterator.remove();
                            read(selector, key);
                        }
                        if (key.isWritable()) {
                            keysIterator.remove();
                            write(selector, key);
                        }
                    }
                } catch (Exception ignore) {
                }
            }
        }).start();
    }

    private void read(Selector selector, SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        socketChannel.read(buffer); // can be non-blocking

        buffer.flip();
        socketChannel.register(selector, SelectionKey.OP_WRITE, buffer);
    }

    private void write(Selector selector, SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();

        ByteBuffer buffer = (ByteBuffer) key.attachment();
        String msg = StandardCharsets.UTF_8.decode(buffer).toString();
        System.out.println(msg);

        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    private void in_read() {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String data = scanner.nextLine();
            out_write(data);
        }
    }

    private void out_write(String data) {
        try {
            socketChannel.write(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));

            this.in_read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
